from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework import serializers, viewsets
from rest_framework.response import Response
from sers.models import book


# Create your views here.
#针对模型设计序列化器
class BookSerializer(serializers.Serializer):
    title = serializers.CharField(max_length=32)
    author = serializers.CharField(max_length=32)
    publisher = serializers.CharField(max_length=32)
    time = serializers.DateTimeField()

    def create(self, validated_data):
        #添加书的数据逻辑
        new_book = book.objects.create(**self.validated_data)
        return new_book
    def update(self, instance, validated_data):
        #添加修改数据的逻辑
        book.objects.filter(pk=instance.pk).update(**validated_data)
        uped_book = book.objects.get(pk=instance.pk)
        return uped_book
class BookView(APIView):
    def get(self, request):
        #获取所有书
        book_list = book.objects.all()
        #构建序列化对象：
        serializer = BookSerializer(instance=book_list, many=True)
        #返回值
        return Response(serializer.data)

    def post(self, request):
        #构建序列化器对象
        serializer = BookSerializer(data=request.data)
        #校验数据
        if serializer.is_valid():
            #返回Ture 执行
            serializer.save()
            return Response(serializer.data)
        else:
            return Response(serializer.errors)

class BookDetailView(APIView):
    def get(self, request, id):
        #获取指定ID的书的信息
        book_detail = book.objects.get(pk=id)
        #构建序列化器对象
        serializer =BookSerializer(instance=book_detail, many=False)
        #返回值
        return Response(serializer.data)

    def put(self, request, id):
        #获取要更新指定ID的书的信息
        up_book = book.objects.get(pk=id)
        #构建序列化器对象
        serializer = BookSerializer(instance=up_book,data=request.data)
        #校验数据
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        else:
            return Response(serializer.errors)
